package pers.gxm.observer;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class FrameObserver extends Frame implements Observer, ActionListener {
    public static void main(String[] args) {
        RandomNumberGenerator generator = new RandomNumberGenerator();
        generator.addObserver(new DigitObserver());
        generator.addObserver(new GraphObserver());
        generator.addObserver(new FrameObserver());
        generator.execute();
    }
    private GraphText textGraph = new GraphText(60);
    private GraphCanvas canvas = new GraphCanvas();
    private Button close = new Button("Close");

    public FrameObserver(){
        super("FrameObserver");
        setLayout(new BorderLayout());
        setBackground(Color.lightGray);
        textGraph.setEditable(false);
        canvas.setSize(500,500);
        add(textGraph,BorderLayout.NORTH);
        add(canvas,BorderLayout.CENTER);
        add(close,BorderLayout.SOUTH);
        close.addActionListener(this);
        pack();
        show();
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("e = " + e);
        System.exit(0);
    }

    @Override
    public void update(NumberGenerator numberGenerator) {
        textGraph.update(numberGenerator);
        canvas.update(numberGenerator);
    }
}

class GraphText extends TextField implements Observer{
    public GraphText(int columns){
        super(columns);
    }

    @Override
    public void update(NumberGenerator numberGenerator) {
        int number = numberGenerator.getNumber();
        String text = number + ":";
        for(int i = 0; i < number;i++){
            text += '*';
        }
        setText(text);
    }
}

class GraphCanvas extends Canvas implements Observer {
    private int number;

    @Override
    public void update(NumberGenerator numberGenerator) {
        number = numberGenerator.getNumber();
        repaint();
    }

    public void paint(Graphics g){
        int width = getWidth();
        int height = getHeight();
        g.setColor(Color.white);
        g.fillArc(0,0,width,height,0,360);
        g.setColor(Color.red);
        g.fillArc(0,0,width,height,90,- number * 360 / 50);
    }
}
